package com.example.templateapp.ui.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.templateapp.R
import com.example.templateapp.model.ChatInfoVo
import com.xuexiang.xui.adapter.recyclerview.RecyclerViewHolder

class ChatAdapter(val context: Context) : RecyclerView.Adapter<RecyclerViewHolder>() {

    private val dataList = mutableListOf<ChatInfoVo>()


    override fun getItemViewType(position: Int): Int {
        return if (dataList[position].isSelf!!) 0 else 1
    }

    fun refresh(data: Collection<ChatInfoVo>) {
        dataList.clear()
        dataList.addAll(data)
        notifyDataSetChanged()
    }

    fun add(info: ChatInfoVo) {
        dataList.add(info)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolder {
        val layoutInflater = LayoutInflater.from(context)
        return if (viewType == 0) {
            ChatSelfViewHolder(layoutInflater, parent)
        } else {
            ChatOtherViewHolder(layoutInflater, parent)
        }
    }

    override fun getItemCount(): Int {
        return dataList.size
    }

    private fun getItem(position: Int): ChatInfoVo {
        return dataList[position]
    }

    override fun onBindViewHolder(holder: RecyclerViewHolder, position: Int) {
        val item = getItem(position)
        holder.text(R.id.chat_content, item.content)
        holder.text(R.id.chat_time, item.time)
    }
}